import * as Form from "@radix-ui/react-form";
import "./teachchForm.css";
import { baseInfoPersonForm3 } from "../utils/data";
import { createBaseInfo, getFile, search } from "../apis/form";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import logo from "../assets/dance-logo.jpg";
import { useState } from "react";
import { pca } from "area-data";
import { AreaSelect, AreaCascader } from "react-area-linkage";

const FormDemo = () => {
  const [alSearch, setAlSearch] = useState(false);
  const [image, setImage] = useState(null);
  const [certType, setCertType] = useState("jyz");
  const [area, setArea] = useState([]);

  const handleSubmit = async (event) => {
    const data = Object.fromEntries(new FormData(event.currentTarget));

    event.preventDefault();
    // 这里可以添加提交表单的逻辑

    if (certType === "hzdwz") {
      data.holderType = 2;
      data.region = area?.join("/");
    }
    if (certType === "jshyz") {
      data.holderType = 1;
    }

    console.log("Submitted name:", data);

    const resp = await search(data);
    console.log(resp?.data?.data?.list);
    const list = resp?.data?.data?.list;
    setAlSearch(false);
    if (list.length === 0) {
      setAlSearch(true);
      // toast.error("该搜索条件暂无数据，请调整条件重试．");
    } else {
      const firstFileData = list?.[0];
      const fileResp = await getFile({
        id: firstFileData.certificateId,
        // certNo: firstFileData.serialNumber
      });
      console.log("fileResp", fileResp);
      if (fileResp.data.data) {
        setAlSearch(true);
        setImage(`data:image/png;base64,${fileResp.data.data}`);
      } else {
        setAlSearch(true);
        // toast.error("该数据暂未证书,清少");
      }
    }
    // if (resp.data?.code === 0) {
    //   toast.success("申请成功");
    // } else {
    //   toast.error(resp?.data?.msg);
    // }
  };

  const handleAreaChange = (val) => {
    setArea(val);
  };

  const renderFormItem = (item) => {
    switch (item.type) {
      case "select":
        return (
          <Form.Control asChild className="mt-[10px]">
            <select
              className="Input"
              required
              onChange={(e) => {
                const value = e.target.value;
                console.log("[value]", value);
                setCertType(value);
              }}
            >
              {item.options?.map((item) => {
                return (
                  <option value={item.value} key={item.value}>
                    {item.label}
                  </option>
                );
              })}
            </select>
          </Form.Control>
        );

      case "textarea":
        return (
          <Form.Control asChild className="mt-[10px]">
            <textarea className="Textarea" rows="4" required />
          </Form.Control>
        );

      case "number":
        return (
          <Form.Control asChild className="mt-[10px]">
            <input className="Input" type="number" required />
          </Form.Control>
        );

      case "date":
        return (
          <Form.Control asChild className="mt-[10px]">
            <input
              type="date"
              className="Date"
              name={item.key}
              required
              defaultValue={item.default}
            />
          </Form.Control>
        );

      case "area":
        return (
          <div className="flex">
            <AreaSelect
              type="text"
              level={2}
              data={pca}
              onChange={handleAreaChange}
            />
          </div>
        );
    }

    return (
      <Form.Control asChild className="mt-[10px]">
        <input className="Input" required />
      </Form.Control>
    );
  };

  return (
    <div>
      <ToastContainer></ToastContainer>

      <div className="px-[20px] py-[20px] text-center flex justify-center mb-[10px] mt-[20px] logoContainer pb-[20px] pt-[10px] flex-col items-center">
        <img className="w-[160px] mb-[40px]" src={logo} alt="" />

        <h2 className="mb-[20px] text-[24px] font-bold text-center">
          中华儿童文化艺术促进会舞蹈专业委员会-证书查询
        </h2>
        <div
          className=""
          style={{
            textAlign: "left",
            lineHeight: "26px",
            letterSpacing: "1px",
          }}
        >
          儿促会舞蹈专业委员会官方主体账号公众平台是查询证书唯的官方渠道，且永久免费查询。请勿通过其他渠道提交个人信息的查询，由此造成的信息泄露我会不承担任何责任。
        </div>
      </div>

      <div className="px-[20px] py-[20px]">
        {!alSearch && (
          <Form.Root className="FormRoot" onSubmit={handleSubmit}>
            {baseInfoPersonForm3.map((item) => {
              if (item.depend) {
                console.log("[certType]", item.depend.certType, certType);
                if (!item.depend.certType.includes(certType)) return null;
              }

              return (
                <Form.Field
                  key={item.key}
                  className="FormField"
                  name={item.key}
                >
                  <div>
                    <Form.Label className="FormLabel font-bold">
                      {item.label}
                    </Form.Label>
                  </div>
                  {renderFormItem(item)}

                  <Form.Message
                    className="FormMessage mt-[10px] text-[red]"
                    match="valueMissing"
                  >
                    请填写{item.label}
                  </Form.Message>
                </Form.Field>
              );
            })}

            <Form.Submit asChild>
              <button type="submit" className="Button mt-[20px]">
                提交
              </button>
            </Form.Submit>
          </Form.Root>
        )}

        {alSearch && (
          <>
            {image && (
              <img src={image} style={{ width: "100%", height: "auto" }}></img>
            )}

            {!image && (
              <div className="flex-center">
                <div className="flex-center text-[24px]">
                  该搜索条件暂无数据，请调整条件重试。
                </div>
              </div>
            )}

            <button
              type="submit"
              className="Button mt-[50px]"
              onClick={() => {
                setImage(null);
                setAlSearch(false);
                setCertType("jyz");
              }}
            >
              返回
            </button>
          </>
        )}
      </div>
    </div>
  );
};

export default FormDemo;
